﻿<template>
  <div class="suppliers-page">
    <el-card>
      <template #header>
        <div class="page-header">
          <h3>供应商管理</h3>
          <el-button type="primary" @click="showAddDialog">
            <el-icon><Plus /></el-icon>
            新增供应商
          </el-button>
        </div>
      </template>

      <div class="search-area">
        <el-form :model="searchForm" inline>
          <el-form-item label="供应商名称">
            <el-input v-model="searchForm.name" placeholder="请输入供应商名称" clearable />
          </el-form-item>
          <el-form-item label="联系人">
            <el-input v-model="searchForm.contact" placeholder="请输入联系人" clearable />
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
              <el-option label="启用" value="启用" />
              <el-option label="禁用" value="禁用" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <el-table :data="tableData" v-loading="loading" stripe>
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="code" label="供应商编码" width="120" />
        <el-table-column prop="name" label="供应商名称" width="200" />
        <el-table-column prop="contact" label="联系人" width="120" />
        <el-table-column prop="phone" label="联系电话" width="130" />
        <el-table-column prop="email" label="邮箱" width="200" />
        <el-table-column prop="address" label="地址" />
        <el-table-column prop="category" label="供应类别" width="120" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === '启用' ? 'success' : 'danger'">
              {{ row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="warning" size="small" @click="handleViewProducts(row)">
              商品
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="supplierFormRef"
        :model="supplierForm"
        :rules="supplierRules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="供应商编码" prop="code">
              <el-input v-model="supplierForm.code" placeholder="请输入供应商编码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供应商名称" prop="name">
              <el-input v-model="supplierForm.name" placeholder="请输入供应商名称" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="联系人" prop="contact">
              <el-input v-model="supplierForm.contact" placeholder="请输入联系人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="supplierForm.phone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="supplierForm.email" placeholder="请输入邮箱" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供应类别" prop="category">
              <el-select v-model="supplierForm.category" placeholder="请选择供应类别" style="width: 100%">
                <el-option label="电子产品" value="电子产品" />
                <el-option label="服装鞋帽" value="服装鞋帽" />
                <el-option label="家居用品" value="家居用品" />
                <el-option label="食品饮料" value="食品饮料" />
                <el-option label="办公用品" value="办公用品" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="地址" prop="address">
          <el-input v-model="supplierForm.address" placeholder="请输入详细地址" />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="supplierForm.status">
            <el-radio label="启用">启用</el-radio>
            <el-radio label="禁用">禁用</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input 
            v-model="supplierForm.remark" 
            type="textarea" 
            :rows="3"
            placeholder="请输入备注信息" 
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          确定
        </el-button>
      </template>
    </el-dialog>

    <el-dialog
      v-model="productsDialogVisible"
      title="供应商商品"
      width="800px"
    >
      <el-table :data="supplierProducts" stripe>
        <el-table-column prop="code" label="商品编码" width="120" />
        <el-table-column prop="name" label="商品名称" width="200" />
        <el-table-column prop="specification" label="规格" width="150" />
        <el-table-column prop="unit" label="单位" width="80" />
        <el-table-column prop="purchasePrice" label="采购价" width="100">
          <template #default="{ row }">
            ¥{{ row.purchasePrice }}
          </template>
        </el-table-column>
        <el-table-column prop="supplyPrice" label="供应价" width="100">
          <template #default="{ row }">
            ¥{{ row.supplyPrice }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === '启用' ? 'success' : 'danger'">
              {{ row.status }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Refresh, Edit, Delete } from '@element-plus/icons-vue'

// 响应式数据
const loading = ref(false)
const dialogVisible = ref(false)
const productsDialogVisible = ref(false)
const submitLoading = ref(false)
const supplierFormRef = ref()

// 搜索表单
const searchForm = reactive({
  name: '',
  contact: '',
  status: ''
})

// 供应商表单
const supplierForm = reactive({
  id: null,
  code: '',
  name: '',
  contact: '',
  phone: '',
  email: '',
  address: '',
  category: '',
  status: '启用',
  remark: ''
})

// 表单验证规则
const supplierRules = {
  code: [
    { required: true, message: '请输入供应商编码', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入供应商名称', trigger: 'blur' }
  ],
  contact: [
    { required: true, message: '请输入联系人', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择供应类别', trigger: 'change' }
  ]
}

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 表格数据
const tableData = ref([
  {
    id: 1,
    code: 'S001',
    name: '苹果供应商',
    contact: '张经理',
    phone: '13800138000',
    email: 'zhang@apple.com',
    address: '北京市朝阳区科技园区',
    category: '电子产品',
    status: '启用',
    remark: '苹果官方授权供应商',
    createTime: '2024-01-01 10:00:00'
  },
  {
    id: 2,
    code: 'S002',
    name: '耐克供应商',
    contact: '李经理',
    phone: '13800138001',
    email: 'li@nike.com',
    address: '上海市浦东新区',
    category: '服装鞋帽',
    status: '启用',
    remark: '耐克品牌授权供应商',
    createTime: '2024-01-02 10:00:00'
  },
  {
    id: 3,
    code: 'S003',
    name: '宜家供应商',
    contact: '王经理',
    phone: '13800138002',
    email: 'wang@ikea.com',
    address: '广州市天河区',
    category: '家居用品',
    status: '启用',
    remark: '宜家家居供应商',
    createTime: '2024-01-03 10:00:00'
  }
])

// 供应商商品数据
const supplierProducts = ref([
  {
    code: 'P001',
    name: 'iPhone 15',
    specification: '128GB 黑色',
    unit: '台',
    purchasePrice: 5000,
    supplyPrice: 4800,
    status: '启用'
  },
  {
    code: 'P002',
    name: 'MacBook Pro',
    specification: '13英寸 M2芯片',
    unit: '台',
    purchasePrice: 12000,
    supplyPrice: 11500,
    status: '启用'
  }
])

// 计算属性
const isEdit = computed(() => !!supplierForm.id)
const dialogTitle = computed(() => isEdit.value ? '编辑供应商' : '新增供应商')

// 方法
const loadData = () => {
  loading.value = true
  setTimeout(() => {
    pagination.total = tableData.value.length
    loading.value = false
  }, 500)
}

const handleSearch = () => {
  pagination.currentPage = 1
  loadData()
}

const handleReset = () => {
  Object.assign(searchForm, {
    name: '',
    contact: '',
    status: ''
  })
  handleSearch()
}

const showAddDialog = () => {
  dialogVisible.value = true
  resetForm()
}

const handleEdit = (row) => {
  dialogVisible.value = true
  Object.assign(supplierForm, { ...row })
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该供应商吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const index = tableData.value.findIndex(item => item.id === row.id)
    if (index > -1) {
      tableData.value.splice(index, 1)
      ElMessage.success('删除成功')
      loadData()
    }
  } catch {
    // 用户取消删除
  }
}

const handleViewProducts = (row) => {
  productsDialogVisible.value = true
  // 这里可以根据供应商ID加载对应的商品数据
}

const handleSubmit = async () => {
  if (!supplierFormRef.value) return

  try {
    await supplierFormRef.value.validate()
    submitLoading.value = true

    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))

    if (isEdit.value) {
      // 编辑供应商
      const index = tableData.value.findIndex(item => item.id === supplierForm.id)
      if (index > -1) {
        tableData.value[index] = { ...supplierForm }
      }
      ElMessage.success('编辑成功')
    } else {
      // 新增供应商
      const newSupplier = {
        ...supplierForm,
        id: Date.now(),
        createTime: new Date().toLocaleString()
      }
      tableData.value.unshift(newSupplier)
      ElMessage.success('新增成功')
    }

    dialogVisible.value = false
    loadData()
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    submitLoading.value = false
  }
}

const handleDialogClose = () => {
  resetForm()
}

const resetForm = () => {
  Object.assign(supplierForm, {
    id: null,
    code: '',
    name: '',
    contact: '',
    phone: '',
    email: '',
    address: '',
    category: '',
    status: '启用',
    remark: ''
  })
  supplierFormRef.value?.clearValidate()
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  loadData()
}

const handleCurrentChange = (page) => {
  pagination.currentPage = page
  loadData()
}

// 生命周期
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.suppliers-page {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-header h3 {
  margin: 0;
  color: #303133;
}

.search-area {
  margin-bottom: 20px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 4px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>
